package com.haliyoo.adhere.widget;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.haliyoo.adhere.R;
import com.haliyoo.adhere.activity.LoginActivity;
import com.haliyoo.adhere.bean.WeiboBean;
import com.haliyoo.adhere.controller.Constants;
import com.haliyoo.adhere.util.BitmapGet;
import com.haliyoo.adhere.util.DateUtilsDef;
import com.haliyoo.adhere.widget.AsyncImageLoader.ImageCallback;
import com.sina.weibo.view.PullToRefreshListView;
import com.sina.weibo.view.PullToRefreshListView.OnRefreshListener;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public abstract class WeiboLayout {
	private static String TAG = "WeiboLayout";
	private Context context = null;
	protected static List<WeiboBean> wbList = null;
	private static final String WEIBO_FILE_NAME = "weibolist.ser";
	private static final String LAST_DATE_FILE_NAME = "lastdate.ser";
	private static final String WEIBO_DIR = Environment
			.getExternalStorageDirectory()
			+ "/adhere/userinfo/" + LoginActivity.getUser().getUser() + "/";
    private PullToRefreshListView weibolist = null;
	private static Date lastDate = null;
	private static TextView tvMoreWeibo = null;
	private LinearLayout mLoadView = null;
	private LayoutInflater mInflater = null;
	private ProgressBar mLoadViewProgress = null;
	private TextView mLoadViewText = null;
	private WeiBoAdapater adapater = null;

	protected WeiboLayout(Context context, LinearLayout llContent) {
		// TODO Auto-generated constructor stub
		this.context = context;
		
		/// 创建文件路径
		new File(WEIBO_DIR).mkdirs();// 创建照片的存储目录

		weibolist = (PullToRefreshListView) ((Activity) context)
				.findViewById(R.id.LIST_VIEW_WEIBO);
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		mLoadView = (LinearLayout) mInflater.inflate(
				R.layout.pull_to_load_footer, null);
		mLoadViewProgress = (ProgressBar) mLoadView
				.findViewById(R.id.pull_to_refresh_progress);
		mLoadViewText = (TextView) mLoadView
				.findViewById(R.id.pull_to_refresh_text);

		// Set a listener to be invoked when the list should be refreshed.
		weibolist.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				// Do work to refresh the list here.
				new HeaderTask().execute();
			}
		});

		weibolist.addFooterView(mLoadView);
		mLoadView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				new FooterTask().execute();
			}
		});

		weibolist.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view,
					int arg2, long arg3) {
				/// 显示微博内容
				onShowWeiboDetail(arg0, view, arg2, arg3);
			}
		});
		
//		TextView tvMore = (TextView) ((Activity) context).findViewById(R.id.TEXT_VIEW_MORE_CREATIVE);
//		tvMore.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				/// 加载微博列表
//				refreshWeiboList();
//			}
//		});
	}

	public void writeRefreshDate() {
        try {
    		Date nowDate = Calendar.getInstance().getTime();
            FileOutputStream fs = new FileOutputStream(WEIBO_DIR + LAST_DATE_FILE_NAME);   
            ObjectOutputStream os =  new ObjectOutputStream(fs);   
            os.writeObject(nowDate);   
            os.close();   
        } catch(Exception ex) {   
            ex.printStackTrace();   
        }  
	}
	
	public static Date readLastDate() {
		try {
			FileInputStream fs = new FileInputStream(WEIBO_DIR + LAST_DATE_FILE_NAME);
			ObjectInputStream ois = new ObjectInputStream(fs);
			lastDate = (Date) ois.readObject();
			ois.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return lastDate;
	}
	
	/**
	 * 写上次读到的微博，只写25条记录
	 */
	public void writeWeiboList() {
		if (wbList != null) {
	        try{   
	            FileOutputStream fs = new FileOutputStream(WEIBO_DIR + WEIBO_FILE_NAME);   
	            ObjectOutputStream os =  new ObjectOutputStream(fs); 
	            int end = wbList.size() > 25 ? 25 : wbList.size();
	            List<WeiboBean> tmpList = new ArrayList<WeiboBean>();
	            /// 此处不能直接使用wbList.subList(0, end);
	            /// 可能和系统分配内存的机制有关系，如果直接使用会报异常。
	            /// 当直接使用时，tmpList的空间只有end大小，比如20，
	            /// 当分配空间后再赋值的做法，tmpList的空间会比end打，比如27
	            for (int i=0; i<end; i++) {
	            	tmpList.add(i, wbList.get(i));
	            }
	            os.writeObject(tmpList);   
	            os.close();   
	        }catch(Exception ex){   
	            ex.printStackTrace();   
	        }  
		}
	}
	
	@SuppressWarnings("unchecked")
	public void readWeiboList() {
		try {
			FileInputStream fs = new FileInputStream(WEIBO_DIR + WEIBO_FILE_NAME);
			ObjectInputStream ois = new ObjectInputStream(fs);
			wbList = (List<WeiboBean>) ois.readObject();
			ois.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * 显示微博列表的处理
	 */
	void showNewWeiboListHandler() {

    	Message message = null;

    	/// 发送显示进度条的消息
        handler.sendEmptyMessage(Constants.SHOW_PROGRESS_BAR);
    	
    	/// 发送显示微博的消息
        message = handler.obtainMessage(Constants.SHOW_NEW_WEIBO_CONTENT, wbList);
        handler.sendMessage(message);
    	/// 发送隐藏进度条的消息
        handler.sendEmptyMessage(Constants.HIDE_PROGRESS_BAR);
	}
	
	/**
	 * 获取最新的微博并显示微博的处理
	 */
	void getAndShowNewWeiboListHandler() {

    	Message message = null;

    	/// 发送显示进度条的消息
        handler.sendEmptyMessage(Constants.SHOW_PROGRESS_BAR);
    	
        /// 获取微博列表
        List<WeiboBean> tmpList = onGetNewWeiboList();
        if (tmpList != null) {
            if (wbList == null) {
            	wbList = tmpList;
            } else {
            	wbList.addAll(0, tmpList);
            }
        }
    	
    	/// 发送显示微博的消息
        message = handler.obtainMessage(Constants.SHOW_NEW_WEIBO_CONTENT, wbList);
        handler.sendMessage(message);
    	/// 发送隐藏进度条的消息
        handler.sendEmptyMessage(Constants.HIDE_PROGRESS_BAR);
	}

	/**
	 * 获取老（默认20条）的微博并显示微博的处理
	 */
	void getAndShowOldWeiboListHandler() {

    	Message message = null;

    	/// 发送显示进度条的消息
        handler.sendEmptyMessage(Constants.SHOW_PROGRESS_BAR);
    	
        /// 获取微博列表
        List<WeiboBean> tmpList = onGetOldWeiboList();
        if (tmpList != null) {
            if (wbList == null) {
            	wbList = tmpList;
            } else {
            	wbList.addAll(wbList.size(), tmpList);
            }
        }
    	
    	/// 发送显示微博的消息
        message = handler.obtainMessage(Constants.SHOW_OLD_WEIBO_CONTENT, wbList);
        handler.sendMessage(message);
    	/// 发送隐藏进度条的消息
        handler.sendEmptyMessage(Constants.HIDE_PROGRESS_BAR);
	}
	
	/**
	 * 显示微博列表
	 */
	public void showWeiboList(){

		/**
		 * 当微博列表已经获取到时直接显示
		 * 否则刷新列表
		 */
		if (wbList != null) {
			showNewWeiboListHandler();
		} else {
			/// 读文件
			readWeiboList();
			
			if (wbList != null) {
				showNewWeiboListHandler();
			} else {
				refreshNewWeiboList();
			}
		}
	}

	/**
	 * 刷新新的微博列表
	 */
	public void refreshNewWeiboList(){

        //建立新一个新的线程下载微博
        new Thread() {
            @Override
            public void run() {
            	getAndShowNewWeiboListHandler();
            }
        }.start();
	}

	/**
	 * 刷新老的微博列表
	 */
	public void refreshOldWeiboList(){

        //建立新一个新的线程下载微博
        new Thread() {
            @Override
            public void run() {
            	getAndShowOldWeiboListHandler();
            }
        }.start();
	}
	
	/// 发消息加载微博列表
    Handler handler = new Handler() {
        public void handleMessage(Message message) {
        	/// 显示进度条
        	if (message.what == Constants.SHOW_PROGRESS_BAR){
        		//((LinearLayout)message.obj).setVisibility(View.VISIBLE);
        		onStartRefresh();
        	}
        	/// 隐藏进度条
        	else if (message.what == Constants.HIDE_PROGRESS_BAR){
        		//((LinearLayout)message.obj).setVisibility(View.GONE);
        		onStopRefresh();
        	}
        	/// 显示微博
        	else if (message.what == Constants.SHOW_NEW_WEIBO_CONTENT) {
        		if (message.obj != null) {
        			
					// / 当切到其他页面时，有可能造成无法获取weibolist
					if (weibolist == null) {
						Log.w(TAG, "weibolist is null, return.");
						return;
					}

        			adapater = new WeiBoAdapater(context, wbList);
        			weibolist.setAdapter(adapater);
    				/// 保存刷新日期
    				writeRefreshDate();
    				/// 写文件
    	        	writeWeiboList();
    			} else {
    				Toast.makeText(context, R.string.STR_NONE_WEIBO_UPDATE, Toast.LENGTH_SHORT).show();
    			}

//				if (message.what == Constants.SHOW_NEW_WEIBO_CONTENT) {
//					weibolist.onRefreshComplete();
//				}
        	}
        }
    };
    
	public class WeiboHolder {
		public ImageView wbprofile = null;
		public ImageView wbicon = null;
		public TextView wbuser = null;
		public ImageView wbloc = null;
		public TextView wbtime = null;
		public TextView wbtext = null;
		public ImageView wbimage = null;
		public LinearLayout llrepost = null;
		public TextView wbtext_repost = null;
		public ImageView wbimage_repost = null;
		public TextView tweet_form = null;
		public ImageView tweet_redirect_pic = null;
		public TextView tweet_redirect = null;
		public ImageView tweet_comment_pic = null;
		public TextView tweet_comment = null;
	}

	// 微博列表Adapater
	public class WeiBoAdapater extends BaseAdapter {

		private AsyncImageLoader asyncImageLoader;

		private List<WeiboBean> list;
		private Context context;
		LayoutInflater inflater;

		public WeiBoAdapater(Context context, List<WeiboBean> list) {
			super();
			this.list = list;
			this.context = context;
			inflater = LayoutInflater.from(this.context);
		}

		@Override
		public int getCount() {
			return list == null ? 0 : list.size();
		}

		@Override
		public Object getItem(int location) {
			return list.get(location);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			return getWeiboListView(position, convertView, parent);
		}

		public View getMoreWeiboView(int position, View convertView, ViewGroup parent) {
			convertView = LayoutInflater.from(context.getApplicationContext()).inflate(
					R.layout.weibo_more, null);
			
			return convertView;
		}
		
		public View getWeiboListView(int position, View convertView, ViewGroup parent) {
			asyncImageLoader = new AsyncImageLoader();
			
			convertView = inflater.inflate(R.layout.weibo, parent, false);
			WeiboHolder wh = new WeiboHolder();
			wh.wbprofile = (ImageView) convertView.findViewById(R.id.wbprofile);
			wh.wbtext = (TextView) convertView.findViewById(R.id.wbtext);
			wh.wbtime = (TextView) convertView.findViewById(R.id.wbtime);
			wh.wbuser = (TextView) convertView.findViewById(R.id.wbuser);
			wh.wbicon = (ImageView) convertView.findViewById(R.id.wbicon);
			wh.wbloc = (ImageView) convertView.findViewById(R.id.wbloc);
			wh.wbimage = (ImageView) convertView.findViewById(R.id.wbimage);
			wh.llrepost = (LinearLayout) convertView.findViewById(R.id.llrepost);
			wh.wbtext_repost = (TextView) convertView.findViewById(R.id.wbtext_repost);
			wh.wbimage_repost = (ImageView) convertView.findViewById(R.id.wbimage_repost);
			wh.tweet_form = (TextView) convertView.findViewById(R.id.tweet_form);
			wh.tweet_redirect_pic = (ImageView) convertView.findViewById(R.id.tweet_redirect_pic);
			wh.tweet_redirect = (TextView) convertView.findViewById(R.id.tweet_redirect);
			wh.tweet_comment_pic = (ImageView) convertView.findViewById(R.id.tweet_comment_pic);
			wh.tweet_comment = (TextView) convertView.findViewById(R.id.tweet_comment);
			WeiboBean wb = wbList.get(position);
			if (wb != null) {
				convertView.setTag(wb.getWeiboId());
				wh.wbuser.setText(wb.getUser());
				wh.wbtime.setText(getTimeDifferenceStr(wb));
				SpannableString ss = FaceManager.getInstance().convertTextToEmotion(context, wb.getText());
				wh.wbtext.setText(ss);

				/// 图片
				if (wb.getExistImage()) {
					wh.wbicon.setImageResource(R.drawable.pic);
					wh.wbicon.setVisibility(View.VISIBLE);
					wh.wbimage.setVisibility(View.VISIBLE);
					if (wb.getIcon() != null) {
						
					} else if (wb.getIconUrl() != null) {
						wh.wbimage.setTag(wb.getIconUrl());
	                    Drawable cache = asyncImageLoader.loadDrawable(wb.getIconUrl(), wh.wbimage, 
	                    		new ImageCallback(){
	                        public void imageLoaded(Drawable imageDrawable,
	                        		ImageView imageView, String imageUrl) {
	                            BitmapGet.showImgByWidth(imageView, imageDrawable, Constants.THUMB_IMAGE_WIDTH);
	                        }
	                    });
	                    
	                    if (cache != null) 
	                    {
                            BitmapGet.showImgByWidth(wh.wbimage, cache, Constants.THUMB_IMAGE_WIDTH);
	                    }
					}
				} else {
					wh.wbimage.setVisibility(View.GONE);
				}
				
				/// 头像
				if (wb.getProfile() != null) {
					wh.wbprofile.setImageBitmap(wb.getProfile());
				} else if (wb.getProfileUrl() != null) {
					Drawable cachedImage = asyncImageLoader.loadDrawable(wb
							.getProfileUrl(), wh.wbprofile, new ImageCallback() {
	
						public void imageLoaded(Drawable imageDrawable,
								ImageView imageView, String imageUrl) {
							imageView.setImageDrawable(imageDrawable);
						}
	
					});
					if (cachedImage == null) {
						wh.wbprofile.setImageResource(R.drawable.icon);
					} else {
						wh.wbprofile.setImageDrawable(cachedImage);
					}
				}
				
				/// 定位状态
				if (wb.getExistLocation()) {
					wh.wbloc.setVisibility(View.VISIBLE);
					wh.wbloc.setImageResource(R.drawable.location_icon);
				} else {
					wh.wbloc.setVisibility(View.GONE);
				}
				
				/// 转播
				if (wb.getRetweet() != null) {
					wh.llrepost.setVisibility(View.VISIBLE);
					SpannableString ss2 = FaceManager.getInstance()
							.convertTextToEmotion(
									context,
									"@" + wb.getRetweet().getUser() + ":"
											+ wb.getRetweet().getText());
					wh.wbtext_repost.setText(ss2);

					/// 图片
					if (wb.getRetweet().getExistImage()) {
						wh.wbimage_repost.setVisibility(View.VISIBLE);
						Bitmap icon = wb.getRetweet().getIcon();
						String url = wb.getRetweet().getIconUrl();
						if (icon != null) {
							
						} else if (url != null) {
							wh.wbimage_repost.setTag(url);
		                    Drawable cache = asyncImageLoader.loadDrawable(url, wh.wbimage_repost, 
		                    		new ImageCallback(){
		                        public void imageLoaded(Drawable imageDrawable,
		                        		ImageView imageView, String imageUrl) {
		                            BitmapGet.showImgByWidth(imageView, imageDrawable, Constants.THUMB_IMAGE_WIDTH);
		                        }
		                    });
		                    
		                    if (cache != null) 
		                    {
	                            BitmapGet.showImgByWidth(wh.wbimage_repost, cache, Constants.THUMB_IMAGE_WIDTH);
		                    }
						}
					}
				} else {
					wh.wbimage_repost.setVisibility(View.GONE);
				}
				
				/// 来自
				wh.tweet_form.setText(context.getString(R.string.STR_COME_FROM) + wb.getComeString());
				
				/// 转发
				if (wb.getRepostCount() > 0) {
					wh.tweet_redirect_pic.setVisibility(View.VISIBLE);
					wh.tweet_redirect.setText(wb.getRepostCount() + "");
					wh.tweet_redirect.setVisibility(View.VISIBLE);
				}
				
				/// 评论
				if (wb.getCommentCount() > 0) {
					wh.tweet_comment_pic.setVisibility(View.VISIBLE);
					wh.tweet_comment.setText(wb.getCommentCount() + "");
					wh.tweet_comment.setVisibility(View.VISIBLE);
				}
			}

			return convertView;
		}
	}

	public static WeiboBean getWeiboBean(long weiboId) {
		for (WeiboBean wb : wbList) {
			if (wb.getWeiboId() == weiboId) {
				return wb;
			}
		}
		
		return null;
	}

	public static long getMaxReadWeiboId() {
		long maxReadWeiboId = 1; ///<读到的最大微博ID，用于下次更新
		if (wbList != null) {
			for (WeiboBean wb : wbList) {
				if (wb.getWeiboId() > maxReadWeiboId) {
					maxReadWeiboId = wb.getWeiboId();
				}
			}
		}
		
		return maxReadWeiboId;
	}

	public static long getMinReadWeiboId() {
		long minReadWeiboId = Long.MAX_VALUE; ///<读到的最小微博ID，用于下次更新
		if (wbList != null) {
			for (WeiboBean wb : wbList) {
				if (wb.getWeiboId() < minReadWeiboId) {
					minReadWeiboId = wb.getWeiboId();
				}
			}
		}
		
		return minReadWeiboId;
	}
	
	private String getTimeDifferenceStr(WeiboBean wb) {

		Date startDate = wb.getTime();
		Date nowDate = Calendar.getInstance().getTime();
		String timeDifferenceStr = new DateUtilsDef(context).twoDateDistance(
				startDate, nowDate);
		wb.setTimeDifference(timeDifferenceStr + context.getString(R.string.STR_AGO));
		
		return wb.getTimeDifference();
	}
	
	/**
	 * 获取最新的微博列表
	 * @return 微博列表
	 */
	public abstract List<WeiboBean> onGetNewWeiboList();
	
	/**
	 * 显示微博细节
	 * @param arg0 The AdapterView where the click happened.
	 * @param view The view within the AdapterView that was clicked (this will be a view provided by the adapter)
	 * @param arg2 The position of the view in the adapter.
	 * @param arg3 The row id of the item that was clicked.
	 */
	public abstract void onShowWeiboDetail(AdapterView<?> arg0, View view,
			int arg2, long arg3);

	/**
	 * 获取老（默认20条）的微博列表
	 * @return 微博列表
	 */
	public abstract List<WeiboBean> onGetOldWeiboList();
	
	/**
	 * 开始刷新
	 */
	public abstract void onStartRefresh();
	
	/**
	 * 停止刷新
	 */
	public abstract void onStopRefresh();
	
	private class HeaderTask extends AsyncTask<Void, Void, List<WeiboBean>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected List<WeiboBean> doInBackground(Void... params) {
			// Simulates a background job.
        	getAndShowNewWeiboListHandler();
        	
			return null;
		}

		@Override
		protected void onPostExecute(List<WeiboBean> result) {

			// Call onRefreshComplete when the list has been refreshed.
			weibolist.onRefreshComplete();

			super.onPostExecute(result);
		}
	}

	private class FooterTask extends AsyncTask<Void, Void, String[]> {

		@Override
		protected void onPreExecute() {
			mLoadViewProgress.setVisibility(View.VISIBLE);
			mLoadViewText.setText(R.string.pull_to_refresh_refreshing_label);
			super.onPreExecute();
		}

		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			getAndShowOldWeiboListHandler();
			
			return null;
		}

		@Override
		protected void onPostExecute(String[] result) {
			adapater.notifyDataSetChanged();

			mLoadViewProgress.setVisibility(View.INVISIBLE);
			mLoadViewText.setText(R.string.pull_to_refresh_tap_label);

			super.onPostExecute(result);
		}
	}

}
